<template>
  <div>
    <LayoutPanel class="private-common-wrapper">
      <div slot="title" class="title">
        <span>{{ $t('ruleList.title') }}</span>
      </div>
      <rj-table
        :columns="ruleColumns"
        :data-source="authRules"
        :pagination="pagination"
        :loading="loading"
        @change="onChangeTable"
        rowKey="id"
        :row-selection="{
          onChange: onSelectChange,
        }"
      >
        <div slot="customBlock" class="log-opt-wrapper">
          <a-space :size="16">
            <a-dropdown>
              <a-button type="primary">
                <icon-font type="ic-plus" />
                {{ $t('ruleList.add') }}
              </a-button>
              <a-menu slot="overlay">
                <a-menu-item>
                  <a @click="onAddDot1xWired">
                    {{ $t('quickCreate.dot1xAll') }}
                  </a>
                </a-menu-item>
                <a-menu-item>
                  <a @click="onAddPortal">
                    {{ $t('quickCreate.portal') }}
                  </a>
                </a-menu-item>
              </a-menu>
            </a-dropdown>
            <a-button @click="onBatchDelete()">
              {{ $t('common.batchDelete') }}
            </a-button>
          </a-space>
          <a-input-search
            :placeholder="$t('quickCreate.ruleName')"
            v-model="queryParamObj.ruleName"
            @change="inputChange"
            style="width: 200px"
          />
        </div>

        <!-- 认证方式 -->
        <template slot="authModeType" slot-scope="text">
          {{ getAuthModeTxt(text) }}
        </template>

        <!-- 用户源 -->
        <template slot="accountSource" slot-scope="text, record">
          <div class="item-wrapper">
            <div
              :key="'source' + index"
              v-for="(source, index) in getUserSourceList(record)"
              class="policy-item"
              @click="gotoSource(source.type)"
            >
              <div class="policy-content" :class="source.type">
                <div class="policy-type">
                  {{ getUserSourceType(source.type) }}
                </div>
                {{ getUserSourceName(source) }}
              </div>
            </div>
          </div>
        </template>

        <!-- 设备组 -->
        <template slot="deviceGroup" slot-scope="text, record">
          <div class="group-item">
            <span class="num">{{
              record.areaList ? record.areaList.length : 0
            }}</span>
            <a-popover
              :destroyTooltipOnHide="true"
              trigger="click"
              @visibleChange="onChangeGroupDetailVisible"
            >
              <template slot="content">
                <rj-table
                  class="reason-table"
                  :columns="reasonColumns"
                  :data-source="record.areaList"
                  :rowKey="(row) => row.content"
                  :pagination="groupPagination"
                  @change="onChangeGroupTable"
                >
                </rj-table>
              </template>
              <icon-font class="not-support-icon" type="ic-prof-list" />
            </a-popover>
          </div>
        </template>

        <!-- 生效条件 -->
        <!-- <template slot="networkInfo" slot-scope="text, record">
          <div class="item-wrapper">
            <div
              :key="'network' + index"
              v-for="(networkInfo, index) in record.networkInfoList"
              :class="[networkInfo.type === 'all' ? '' : 'network-item']"
            >
              <icon-font type="ic-wifi" v-if="networkInfo.type === 'ssid'" />
              {{ getNetworkInfoName(networkInfo) }}
            </div>
          </div>
        </template> -->

        <!-- 操作 -->
        <template slot="action" slot-scope="text, record">
          <rj-space :size="16">
            <icon-font
              v-if="[2, 3].includes(record.authModeType)"
              type="ic-clue"
              @click="onTest(record)"
              :title="$t('thirdPart.connTest')"
            ></icon-font>
            <icon-font
              type="ic-edit"
              @click="onEdit(record)"
              :title="$t('common.edit')"
            ></icon-font>
            <icon-font
              type="ic-delete"
              @click="onDelete(record)"
              :title="$t('common.delete')"
            ></icon-font>
          </rj-space>
        </template>
      </rj-table>
    </LayoutPanel>
    <portalAuthEditor
      v-if="loadSourceList"
      @refreshList="refreshView"
      ref="portalAuthEditorRef"
    ></portalAuthEditor>
    <dot1xWiredEditor
      v-if="loadSourceList"
      @refreshList="refreshView"
      ref="dot1xWiredEditorRef"
    />
    <connTestModal ref="connTestModalRef" />
    <dot1xWiredCreator
      v-if="loadSourceList"
      @refreshList="refreshView"
      ref="dot1xWiredCreatorRef"
    />
    <portalAuthCreator
      v-if="loadSourceList"
      @refreshList="refreshView"
      ref="portalAuthCreatorRef"
    />
  </div>
</template>

<script>
import { maccApi } from '@utils/index';
import { RjTable } from '@components';
import portalAuthCreator from '../quickCreate/portalAuthCreator';
import dot1xWiredCreator from '../quickCreate/dot1xWiredCreator';
import { ruleColumns } from './columns.js';
import portalAuthEditor from './portalAuthEditor';
import dot1xWiredEditor from './dot1xWiredEditor';
import connTestModal from './connTestModal';
import LayoutPanel from '@views/common/deviceDetail/components/components/layoutPanel.vue';
import lodash from 'lodash';
import authSysMixin from '@project/authSys/mixin/authSysMixin';
import { mapState } from 'vuex';
export default {
  name: 'ruleList',
  mixins: [authSysMixin],
  data() {
    return {
      loading: false,
      ruleColumns,
      authRules: [],
      pagination: {
        current: 1,
        total: 0,
        pageSize: 10,
        showSizeChanger: true,
        showQuickJumper: true,
      },
      queryParamObj: {
        ruleName: '',
      },
      selectedRowKeys: [],
      reasonColumns: [
        {
          title: this.$t('ruleList.bindedGroup'), // 'Bind Device Group',
          dataIndex: 'name',
          width: 300,
        },
      ],
      groupPagination: {
        total: 0,
        current: 1,
        pageSize: 5,
        showSizeChanger: false,
        showQuickJumper: false,
      },
      loadSourceList: false,
    };
  },
  async mounted() {
    this.loadSourceList = false;
    await this.get3rdSourceList();
    this.getRuleList();
    this.getAuthDeviceGroupList();
    this.getTwillioInfo();
  },
  components: {
    'rj-table': RjTable,
    LayoutPanel,
    portalAuthEditor,
    dot1xWiredEditor,
    connTestModal,
    portalAuthCreator,
    dot1xWiredCreator,
  },
  computed: {
    ...mapState('AuthCommon', ['thirdPartSources']),
  },
  methods: {
    refreshView() {
      this.getRuleList();
      this.getAuthDeviceGroupList();
    },
    onBatchDelete() {
      if (!this.selectedRowKeys.length) {
        this.$message.warning(this.$t('common.oneData'));
        return;
      }
      const self = this;
      this.$confirm({
        title: this.$t('common.batchDelete'),
        content: this.$t('ruleList.deleteConfirm'),
        onOk() {
          self.deleteRule(self.selectedRowKeys.join(','));
        },
      });
    },

    async deleteRule(ids) {
      let querys = {
        ids,
      };
      const res = await this.requestHttpAuth({
        api: `${maccApi.MACC_RULE_BATCH_DEL_API}`,
        method: 'DELETE',
        querys,
      });

      if (res.data.success) {
        this.$message.success(this.$t('common.delSuccess'));
        this.pagination.current = 1;
        this.getRuleList();
        this.getAuthDeviceGroupList();
      } else {
        this.$message.warning(res.data.message);
      }
    },

    onAddDot1xWired() {
      this.$refs.dot1xWiredCreatorRef.openEditor();
    },
    onAddPortal() {
      this.$refs.portalAuthCreatorRef.openEditor();
    },
    async getTwillioInfo() {
      let res = await this.requestHttpAuth({
        api: maccApi.MACC_BAAS_GET_API,
        replaces: {
          tenantName: this.tenantInfo.tenantName,
        },
        querys: {
          tenantId: this.tenantInfo.tenantId,
        },
        method: 'GET',
      });
      if (!res.data.code) {
        const tempForm = {};
        tempForm.sid = res.data.smsSid;
        tempForm.authToken = res.data.smsToken;
        tempForm.authPhone = res.data.smsFromPhoneNumber;
        this.$store.commit('PortalAuth/SET_TWILLIO', tempForm);
      } else {
        this.$message.warning(res.data.msg);
      }
    },
    gotoSource(sourceType) {
      switch (sourceType) {
        case 'ad':
        case 'ldap':
          this.$router.push('authConf_thirdPart_menu');
          break;
        case 'voucher':
          this.$router.push('authConf_authVoucher_menu');
          break;
        case 'mac':
          this.$router.push('authConf_authMac_menu');
          break;
        case 'local':
          this.$router.push('authConf_localAccount_menu');
          break;
        default:
      }
    },
    onChangeGroupTable(pagination) {
      this.groupPagination.current = pagination.current;
    },
    onChangeGroupDetailVisible(visible) {
      if (!visible) {
        this.groupPagination.current = 1;
      }
    },
    async getAuthDeviceGroupList() {
      const res = await this.requestHttpAuth({
        api: maccApi.PRIVATE_DEVICE_GROUP_GET_API,
        method: 'GET',
        querys: {
          groupId: this.groupId,
          page: 1,
          size: 100,
        },
      });

      if (res.data.success) {
        this.$store.commit(
          'AuthCommon/SET_DEVICE_GROUP_LIST',
          res.data.result.items
        );
      } else {
        this.$message.warning(res.data.message);
      }
    },

    // 表格复选框勾选事件
    onSelectChange(selectedRowKeys) {
      this.selectedRowKeys = selectedRowKeys;
    },
    onTest() {
      this.$refs.connTestModalRef.openModal();
    },
    onEdit(record) {
      switch (record.authModeType) {
        case 2:
          this.$refs.dot1xWiredEditorRef.openEditor(record);
          break;
        case 1:
        default:
          this.$refs.portalAuthEditorRef.openEditor(record);
      }
    },
    onAdd() {
      this.$router.push('authConf_quickCreate_menu');
    },
    getAuthModeTxt(authMode) {
      switch (authMode) {
        case 2:
        case 3:
          return '802.1X';
        case 4:
          return this.$t('authLog.mab');
        case 1:
        default:
          return this.$t('authHome.portal');
      }
    },

    getUserSourceList(record) {
      if ([2, 3].includes(record.authModeType)) {
        const userSources = [
          {
            id: -1,
            type: 'local',
          },
          {
            id: -3,
            type: 'mac',
          },
        ];
        for (const source of this.thirdPartSources) {
          userSources.push({
            id: source.id,
            type: source.type,
            name: source.name,
          });
        }
        return userSources;
      } else {
        return record.accountSourceList;
      }
    },

    getUserSourceType(userSourceType) {
      switch (userSourceType) {
        case 'ad':
          return 'AD';
        case 'ldap':
          return 'LDAP';
        case 'local':
          return 'ACCOUNT';
        case 'mac':
          return 'MAC';
        case 'voucher':
        default:
          return 'VOUCHER';
      }
    },

    getUserSourceName(source) {
      switch (source.type) {
        case 'local':
          return 'Local Acount';
        case 'voucher':
          return 'Local Voucher';
        case 'mac':
          return 'Local MAC';
        default:
          return source.name;
      }
    },

    getNetworkInfoName(networkInfo) {
      if (networkInfo.type === 'all') {
        return this.$t('quickCreate.allSsid');
      } else {
        return networkInfo.ssid;
      }
    },

    inputChange() {
      this.getRuleList();
    },

    onDelete(row) {
      if (!row) {
        if (!this.selectedRowKeys.length) {
          this.$message.warning(this.$t('ruleList.selectOneRule'));
          return;
        }
      }

      let ids = '';
      if (row) {
        ids = row.id;
      } else {
        this.selectedRowKeys.forEach((item) => {
          ids += item.id + ',';
        });
      }

      this.$confirm({
        title: this.$t('common.delete'),
        content: this.$t('ruleList.deleteConfirm'),
        onOk: async () => {
          await this.deleteRule(ids);
          // let querys = {
          //   ids,
          // };
          // const res = await this.requestHttpAuth({
          //   api: `${maccApi.MACC_RULE_BATCH_DEL_API}`,
          //   method: 'DELETE',
          //   querys,
          // });

          // if (res.data.success) {
          //   this.$message.success(this.$t('common.delSuccess'));
          //   this.pagination.current = 1;
          //   this.getRuleList();
          // } else {
          //   this.$message.warning(res.data.message);
          // }
        },
      });
    },

    getListDebounce: lodash.debounce(function () {
      this.getRuleList();
    }, 1500),

    async getRuleList() {
      const res = await this.requestHttpAuth({
        api: maccApi.MACC_RULE_GET_API,
        method: 'GET',
        querys: {
          groupId: this.groupId,
          page: this.pagination.current,
          size: this.pagination.pageSize,
          name: this.queryParamObj.ruleName,
        },
      });

      if (res.data.success) {
        this.pagination.total = res?.data?.result?.total || 0;
        this.authRules = res?.data?.result?.items || [];
      } else {
        this.$message.warning(res.data.message);
      }
    },

    //table表格分页变化时触发
    onChangeTable(pagination, filterObj, sorter) {
      this.pagination.current = pagination.current;
      this.pagination.pageSize = pagination.pageSize;
      this.getRuleList();
    },

    // 查询数据
    async get3rdSourceList() {
      const res = await this.requestHttpAuth({
        api: maccApi.MACC_SOURCE_GET_API,
        replaces: {
          tenantName: this.tenantInfo.tenantName,
          groupId: this.groupId,
        },
        querys: {
          tenantId: this.tenantInfo.tenantId,
          page: 1,
          pageSize: 100,
        },
        method: 'GET',
      });

      if (res.data.success) {
        this.thirdParts = res?.data?.result?.items || [];
        this.$store.commit('AuthCommon/SET_3RD_SOURCE_LIST', this.thirdParts);
        this.loadSourceList = true;
      } else {
        this.$message.warning(res.data.message);
        this.loadSourceList = true;
      }
    },
  },
};
</script>

<style lang="less" scoped>
.private-common-wrapper {
  padding: 16px;
  height: 100%;
  overflow-y: auto;
  .title {
    display: flex;
    justify-content: space-between;
  }
}
.group-item {
  display: flex;
  align-items: center;
  gap: 8px;
  .num {
    display: inline-block;
    width: 50px;
    text-align: right;
  }
  i {
    color: @theme-color;
    font-size: 18px;
    cursor: pointer;
  }
}
/deep/.defultWapper {
  margin-left: 0;
}

.log-tip {
  font-size: 12px;
  color: #00000073;
}
.log-opt-wrapper {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  box-sizing: border-box;
}
.add-btn {
  height: 32px;
  display: flex;
  align-items: center;
  i {
    font-size: 18px;
    height: 18px;
  }
}
.item-wrapper {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}
.policy-item {
  font-size: 12px;
  display: inline-block;
}
.policy-content {
  padding: 6px;
  display: flex;
  gap: 4px;
  border-radius: 2px;
  cursor: pointer;
}
.policy-type {
  border-radius: 2px;
  padding: 0 4px;
  color: #fff;
}
.ad,
.ldap {
  border: 1px solid @success-focus;
  color: @success-color;
  .policy-type {
    background: @success-color;
  }
  &:hover {
    background: @success-light;
  }
}
.voucher,
.local,
.mac {
  border: 1px solid @theme-focus;
  color: @theme-color;
  .policy-type {
    background: @theme-color;
  }
  &:hover {
    background: @theme-light;
  }
}
.network-item {
  border: 1px solid @component-border;
  border-radius: 2px;
  background: @bg-component;
  font-size: 12px;
  padding: 0 8px;
  display: flex;
  align-items: center;
  gap: 8px;
}
</style>
